package cn.pli.bike.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;

import com.alipay.sdk.app.PayTask;
import com.framemodule.base.BaseActivityPresenter;
import com.framemodule.base.netstatus.NetUtils;
import com.framemodule.utils.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Map;

import cn.pli.bike.R;
import cn.pli.bike.bean.HttpResult;
import cn.pli.bike.bean.OrderinfoBean;
import cn.pli.bike.model.UserModel;
import cn.pli.bike.model.subscribers.ProgramSubscriber;
import cn.pli.bike.utils.AppUtils;
import cn.pli.bike.utils.DialogUtils;
import cn.pli.bike.utils.EventBusAction;
import cn.pli.bike.utils.PayResult;
import cn.pli.bike.utils.UtilData;


/**
 * 缴纳押金界面
 */

public class PaymentDepositActivity extends BaseActivityPresenter<PaymentDepositDelegate> implements View.OnClickListener {

    public static final int TYPE_WXPAY = 1;      //微信支付
    public static final int TYPE_ALIPAY = 2;     //支付宝支付
    private int type = TYPE_WXPAY;
    private IWXAPI msgApi;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        viewDelegate.toast("支付成功");
                        Message message = new Message();
                        message.what = EventBusAction.NOTICE_PAY_DEPOSIT;
                        EventBus.getDefault().post(message);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        viewDelegate.toast("支付失败");
                    }
                    break;
                }


                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void initModel() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //TODO充值
        msgApi = WXAPIFactory.createWXAPI(this, UtilData.APP_ID, false);
        msgApi.registerApp(UtilData.APP_ID);
        viewDelegate.setTvDepositAmount(AppUtils.getDeposit() + "");

        EventBus.getDefault().register(this);

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.setOnClickListener(this, R.id.iv_title_back, R.id.bt_commit);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.bt_commit:
                showChargerType();
                break;
        }

    }

    /**
     * 选择支付方式
     */
    private void showChargerType() {
        final Dialog dialog = DialogUtils.getDownToUpDialog(this, R.layout.alert_dialog_wallet_charger_way);
        Button btGoToPay = dialog.findViewById(R.id.bt_go_to_pay);
        RadioGroup rgType = (RadioGroup) dialog.findViewById(R.id.rg_alert_dialog_wallet_charger);
        rgType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_alert_dialog_wallet_charger_button1:
                        type = TYPE_WXPAY;          //
                        break;
                    case R.id.rb_alert_dialog_wallet_charger_button2:
                        type = TYPE_ALIPAY;
                        break;
                }
            }
        });
        btGoToPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double money = AppUtils.getDeposit();
                switch (type) {
                    case TYPE_ALIPAY:
                        aliPay(money, "0");
                        break;
                    case TYPE_WXPAY:
                        wxPay(money, "0");
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void aliPay(double cashnum, String consumptionType) {
        UserModel.aliPay(new ProgramSubscriber<HttpResult<OrderinfoBean>>() {
            @Override
            public void onNext(HttpResult<OrderinfoBean> orderinfoBeanHttpResult) {
                final String orderInfo = orderinfoBeanHttpResult.getData().getOrderStr();
                Logger.d(orderinfoBeanHttpResult.getData().getOrderStr());
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PaymentDepositActivity.this);
                        Map result = alipay.payV2(orderInfo, true);
                        Log.i("msp", result.toString());
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        }, cashnum, consumptionType);
    }


    /**
     * 微信支付
     *
     * @param cashnum
     * @param consumptionType
     */

    private void wxPay(double cashnum, String consumptionType) {
        UserModel.wxPay(new ProgramSubscriber<HttpResult<String>>() {
            @Override
            public void onNext(HttpResult<String> orderinfoBeanHttpResult) {
                final PayReq req = new PayReq();
                String result = orderinfoBeanHttpResult.getData();
                if (com.framemodule.utils.CommonUtils.isEmpty(result)) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    req.appId = UtilData.APP_ID;
                    req.partnerId = jsonObject.optString("partnerid");
                    req.prepayId = jsonObject.optString("prepayid");
                    req.packageValue = jsonObject.optString("package");
                    req.nonceStr = jsonObject.optString("noncestr");
                    req.timeStamp = jsonObject.optString("timestamp");
                    req.sign = jsonObject.optString("sign");

                } catch (Exception e) {
                    e.printStackTrace();
                }


                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (isWXAppInstalledAndSupported()) {
                            boolean isPay = msgApi.sendReq(req);
                            // finish();
                        } else {
                            Looper.prepare();
                            viewDelegate.toast("未安装微信");//未安装微信
                            Looper.loop();
                        }

                    }
                }).start();

            }
        }, cashnum, consumptionType);
    }

    private boolean isWXAppInstalledAndSupported() {
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 缴纳押金成功后的处理
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlePay(Message messageEvent) {
        if (messageEvent.what == EventBusAction.NOTICE_PAY_DEPOSIT) {
            if (!AppUtils.isAuthStatus()) {
                readyGoThenKill(UserAuthActivity.class);

            } else {
                finish();
            }

        }
    }
}
